package com.ztc.ZtcDriver.web;

import com.alibaba.fastjson.JSONObject;
import com.aqgj.Attachment.bean.Attachment;
import com.aqgj.Attachment.service.AttachmentManager;
import com.aqgj.User.bean.User;
import com.aqgj.User.service.UserManager;
import com.aqgj.common.BaseController;
import com.aqgj.util.DateFarmatUtils;
import com.aqgj.util.JsonWrapper;
import com.aqgj.util.Pager;
import com.aqgj.util.StringUtils;
import com.ztc.ZtcDriver.bean.ZtcDriver;
import com.ztc.ZtcTransport.bean.ZtcTransport;
import com.ztc.ZtcTransport.service.ZtcTransportManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ztc.ZtcDriver.service.ZtcDriverManager;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("ztc_driver_action")
public class  ZtcDriverAction extends BaseController{
    @Autowired
    private ZtcDriverManager  ztcDriverManager;
    @Autowired
    private ZtcTransportManager ztcTransportManager;
    @Autowired
    private AttachmentManager attachmentManager;
    @Autowired
    private UserManager userManager;

    /**
     * 添加保存司机信息.
     * @param ztcDriver 司机信息
     * @param imgString 司机证照
     * @param pageStatus 操作类型
     * @param request
     * @return
     */
    @RequestMapping("saveZtcDriver")
    @ResponseBody
    public HashMap<String, Object> saveZtcDriver(ZtcDriver ztcDriver,HttpSession session,String imgString,HttpServletRequest request,String pageStatus,Date examineTime) {
        User user = (User) session.getAttribute("userInfo");
        ZtcTransport ztcTransport = ztcTransportManager.get(user.getTransportId());
        if(ztcTransport==null){
            return JsonWrapper.failureWrapperMsg("操作失败，请稍后重试！");
        }
        //当前公司状态处于冻结状态，无法操作业务
        if (ztcTransport.getStatus()==4) {
            return JsonWrapper.failureWrapperMsg("公司处于冻结状态，该操作不被允许!");
        }
        if(ztcTransport.getType()!=3&&ztcTransport.getType()!=4){
            return JsonWrapper.failureWrapperMsg("非运营或车方无权限进行该操作！");
        }
        if("add".equals(pageStatus)){
            if(ztcTransport.getType()==4){
                ztcDriver.setStatus("2");
            }else{
                ztcDriver.setStatus("1");
                ztcDriver.setExamineUserId(user.getId());
                ztcDriver.setExamineTime(new Date());
                ztcDriver.setBeginValidateTime(new Date());
                ztcDriver.setExamineRemark("后台新增");
            }
            ztcDriver.setEndValidateTime(examineTime);
            ztcDriver.setSignTime(new Date());
            ztcDriver.setTransportId(ztcTransport.getId());
            String did= ztcDriverManager.save(ztcDriver);
            JSONObject json = JSONObject.parseObject(imgString);
            if(json.size()<4){
                ztcDriverManager.removeById(did);
                return JsonWrapper.failureWrapperMsg("证件资料不全，无法提交数据！");
            }
            if (json.containsKey("head_img")) {
                attachmentManager.saveAttachment(json,"head_img",user,did,request,"添加司机");
            }
            if (json.containsKey("driver_img")) {
                attachmentManager.saveAttachment(json,"driver_img",user,did,request,"添加司机");
            }
            if (json.containsKey("cert_img")) {
                attachmentManager.saveAttachment(json,"cert_img",user,did,request,"添加司机");
            }
            if (json.containsKey("work_img")) {
                attachmentManager.saveAttachment(json,"work_img",user,did,request,"添加司机");
            }
            return JsonWrapper.successWrapper("添加成功！");
        }
        if("modify".equals(pageStatus)){//修改车辆
            ZtcDriver ztcDriver1=ztcDriverManager.get(ztcDriver.getId());
            List<Attachment> list=attachmentManager.getAttachmentByBusinessId(ztcDriver.getId());
            ztcDriver.setTransportId(ztcDriver1.getTransportId());
            ztcDriver.setBeginValidateTime(ztcDriver1.getBeginValidateTime());
            ztcDriver.setExamineUserId(ztcDriver1.getExamineUserId());
            ztcDriver.setModifyRemark(ztcDriver1.getModifyRemark());
            ztcDriver.setExamineUserId(ztcDriver1.getExamineUserId());
            ztcDriver.setSignTime(ztcDriver1.getSignTime());
            ztcDriver.setExamineTime(ztcDriver1.getExamineTime());
            ztcDriver.setExamineRemark(ztcDriver1.getExamineRemark());
            if(examineTime==null){
                ztcDriver.setEndValidateTime(ztcDriver1.getEndValidateTime());
            }else{
                ztcDriver.setEndValidateTime(examineTime);
            }
            JSONObject json = JSONObject.parseObject(imgString);
            if (ztcTransport.getType() == 4) {//车方
                if ("".equals(json.get("driver_img"))&&"".equals(json.get("head_img"))&&"".equals(json.get("work_img"))&&"".equals(json.get("cert_img"))) {//未修改图片
                    ztcDriver.setStatus(ztcDriver1.getStatus());
                } else {//修改图片，需审核
                    ztcDriver.setStatus("2");
                }
            }else{
                ztcDriver.setStatus(ztcDriver1.getStatus());
            }
            String did= ztcDriverManager.update(ztcDriver);
            if (!"".equals(json.get("head_img"))) {
                if(list.size()>0){
                    for (Attachment a:list) {
                        if("head_img".equals(a.getWorkItem())){
                            attachmentManager.deleteAttachment(a);
                        }
                    }
                }
                attachmentManager.saveAttachment(json,"head_img",user,did,request,"修改司机");
            }
            if (!"".equals(json.get("driver_img"))) {
                if(list.size()>0){
                    for (Attachment a:list) {
                        if("driver_img".equals(a.getWorkItem())){
                            attachmentManager.deleteAttachment(a);
                        }
                    }
                }
                attachmentManager.saveAttachment(json,"driver_img",user,did,request,"修改司机");
            }
            if (!"".equals(json.get("cert_img"))) {
                if(list.size()>0){
                    for (Attachment a:list) {
                        if("cert_img".equals(a.getWorkItem())){
                            attachmentManager.deleteAttachment(a);
                        }
                    }
                }
                attachmentManager.saveAttachment(json,"cert_img",user,did,request,"修改司机");
            }
            if (!"".equals(json.get("work_img"))) {
                if(list.size()>0){
                    for (Attachment a:list) {
                        if("work_img".equals(a.getWorkItem())){
                            attachmentManager.deleteAttachment(a);
                        }
                    }
                }
                attachmentManager.saveAttachment(json,"work_img",user,did,request,"修改司机");
            }
            return JsonWrapper.successWrapper("修改成功！");
        }
        return JsonWrapper.failureWrapperMsg("操作失败！");
    }

    /**
     * 获取当前公司所有司机信息(运营获取包括旗下车方司机).
     * @param session  session
     * @param pageSize  分页每页大小
     * @param pageNumber  页码
     * @param search    搜索内容
     * @param status   状态（1表示运营列表，2待审核列表）
     * @return
     */
    @RequestMapping("getDriverList")
    @ResponseBody
	public HashMap<String,Object> getDriverList(HttpSession session,Integer pageSize,Integer pageNumber,String search,String status){
	    User user=(User) session.getAttribute("userInfo");
        ZtcTransport ztcTransport=ztcTransportManager.get(user.getTransportId());
        if(ztcTransport==null){
            return JsonWrapper.failureWrapperMsg("获取司机信息失败！");
        }
        if(StringUtils.isBlank(status)){
            return JsonWrapper.failureWrapperMsg("参数错误，获取失败！");
        }
        Pager<ZtcDriver> ztcDriverList=ztcDriverManager.getDriverListByTransportId(ztcTransport.getId(),pageSize,pageNumber,ztcTransport.getType(),search,status);
        HashMap<String, Object> map = null;
        List<HashMap<String, Object>> list1 = new ArrayList<>();
        if (ztcDriverList.getContent().size() > 0) {
            for (ZtcDriver ztcDriver : ztcDriverList.getContent()) {
                map = new HashMap<>();
                map.put("id", ztcDriver.getId());
                map.put("dStatus", getDriverStatus(ztcDriver.getStatus()));
                map.put("name", ztcDriver.getdName());
                map.put("signTime", ztcDriver.getSignTime());
                map.put("endTime", ztcDriver.getEndValidateTime());
                map.put("phone", ztcDriver.getPhone());
                map.put("status", ztcDriver.getStatus());
                map.put("driverCard",ztcDriver.getDriverCard());
                if("1".equals(status)){
                    map.put("examineUsername",ztcDriver.getExamineUserId()!=null?userManager.get(ztcDriver.getExamineUserId()).getAccount():null);
                    map.put("examineTime",ztcDriver.getExamineTime());
                }
                map.put("transport", ztcTransportManager.get(ztcDriver.getTransportId()).getFullName());
                list1.add(map);
            }
            return JsonWrapper.successPagerWrapper(list1,ztcDriverList.getRecordTotal());
        }
	     return JsonWrapper.successWrapper("");
    }

    /**
     * 获取当前公司所有司机信息(运营获取包括旗下车方司机).
     * @return
     */
    @RequestMapping("getAllDriverList")
    @ResponseBody
    public HashMap<String,Object> getAllDriverList(HttpSession session){
        User user=(User) session.getAttribute("userInfo");
        ZtcTransport ztcTransport=ztcTransportManager.get(user.getTransportId());
        if(ztcTransport==null){
            return JsonWrapper.failureWrapperMsg("获取司机信息失败！");
        }
        List<ZtcDriver> ztcDriverList=ztcDriverManager.getDriverListByTransportId(ztcTransport.getId(),ztcTransport.getType());
        HashMap<String, Object> map = null;
        List<HashMap<String, Object>> list1 = new ArrayList<>();
        if (ztcDriverList.size() > 0) {
            for (ZtcDriver ztcDriver : ztcDriverList) {
                map = new HashMap<>();
                map.put("id", ztcDriver.getId());
                map.put("name", ztcDriver.getdName());
                list1.add(map);
            }
            return JsonWrapper.successWrapper(list1);
        }
        return JsonWrapper.successWrapper("");
    }

    /**
     * 根据司机id获取详情.
     * @param did 司机id
     * @return
     */
    @RequestMapping("getDriverDetail")
    @ResponseBody
    public HashMap<String, Object> getDriverDetail(String did){
        ZtcDriver ztcDriver = ztcDriverManager.get(did);
        if (ztcDriver == null) {
            return JsonWrapper.failureWrapperMsg("不存在该司机！");
        }
        HashMap<String,Object> map=new HashMap<>();
        map.put("name", ztcDriver.getdName());
        map.put("phone", ztcDriver.getPhone());
        map.put("id", ztcDriver.getId());
        map.put("driverCard",ztcDriver.getDriverCard());
        map.put("signTime", ztcDriver.getSignTime());
        map.put("endTime", ztcDriver.getEndValidateTime());
        map.put("status", ztcDriver.getStatus());
        map.put("examineUsername",ztcDriver.getExamineUserId()!=null?userManager.get(ztcDriver.getExamineUserId()).getAccount():null);
        map.put("examineTime",ztcDriver.getExamineTime());
        map.put("dStatus", getDriverStatus(ztcDriver.getStatus()));
        map.put("transport", ztcTransportManager.get(ztcDriver.getTransportId()).getFullName());
        List<Attachment> attachments = attachmentManager.getAttachmentByBusinessId(did);
        if (attachments.size() > 0) {
            for (Attachment a : attachments) {
                if ("head_img".equals(a.getWorkItem())) {
                    map.put("hFilePath", a.getFilePath());
                    map.put("hFileName", a.getFileName());
                    continue;
                }
                if ("driver_img".equals(a.getWorkItem())) {
                    map.put("dFilePath", a.getFilePath());
                    map.put("dFileName", a.getFileName());
                    continue;
                }
                if ("cert_img".equals(a.getWorkItem())) {
                    map.put("cFilePath", a.getFilePath());
                    map.put("cFileName", a.getFileName());
                    continue;
                }
                if ("work_img".equals(a.getWorkItem())) {
                    map.put("wFilePath", a.getFilePath());
                    map.put("wFileName", a.getFileName());
                }
            }
            return JsonWrapper.successWrapper(map);
        }
        return JsonWrapper.failureWrapperMsg("获取信息失败，请稍后重试！");
    }

    /**
     * 根据司机id审核该司机(通过).
     * @param did      司机id
     * @param endTime  审核状态
     * @param remark  审核意见
     * @return
     */
    @RequestMapping("reviewedDriver")
    @ResponseBody
    public HashMap<String, Object> reviewedDriver(String did,Date endTime,String remark,HttpSession session) {
        User user = (User) session.getAttribute("userInfo");
        ZtcTransport ztcTransport1 = ztcTransportManager.get(user.getTransportId());
        if(ztcTransport1.getType()!=3){
            return JsonWrapper.failureWrapperMsg("非运营公司无权限进行该操作！");
        }
        //当前公司状态处于冻结状态，无法操作业务
        if (ztcTransport1.getStatus()==4) {
            return JsonWrapper.failureWrapperMsg("公司处于冻结状态，该操作不被允许!");
        }
        ZtcDriver ztcDriver = ztcDriverManager.get(did);
        if (ztcDriver == null) {
            return JsonWrapper.failureWrapperMsg("不存在该司机！");
        }
        if(!"2".equals(ztcDriver.getStatus())){
            return JsonWrapper.failureWrapperMsg("该司机已审核过！");
        }
        ztcDriver.setEndValidateTime(endTime);
        ztcDriver.setStatus("1");
        ztcDriver.setExamineRemark(remark);
        ztcDriver.setExamineTime(new Date());
        ztcDriver.setBeginValidateTime(new Date());
        ztcDriver.setExamineUserId(user.getId());
        ztcDriverManager.save(ztcDriver);
        return JsonWrapper.successWrapper("操作成功！");
    }

    /**
     * 根据司机id审核该司机（不通过）.
     * @param did      司机id
     * @param remark  审核意见
     * @return
     */
    @RequestMapping("unReviewedDriver")
    @ResponseBody
    public HashMap<String, Object> unReviewedDriver(String did,String remark,HttpSession session) {
        User user = (User) session.getAttribute("userInfo");
        ZtcTransport ztcTransport1 = ztcTransportManager.get(user.getTransportId());
        if (ztcTransport1==null) {
            return JsonWrapper.failureWrapperMsg("网络错误，请稍后重试!");
        }
        if(ztcTransport1.getType()!=3){
            return JsonWrapper.failureWrapperMsg("非运营公司无权限进行该操作！");
        }
        //当前公司状态处于冻结状态，无法操作业务
        if (ztcTransport1.getStatus()==4) {
            return JsonWrapper.failureWrapperMsg("公司处于冻结状态，该操作不被允许!");
        }
        ZtcDriver ztcDriver = ztcDriverManager.get(did);
        if (ztcDriver == null) {
            return JsonWrapper.failureWrapperMsg("不存在该司机！");
        }
        if(!"2".equals(ztcDriver.getStatus())){
            return JsonWrapper.failureWrapperMsg("该司机已审核过！");
        }
        ztcDriver.setStatus("4");
        ztcDriver.setExamineRemark(remark);
        ztcDriver.setExamineTime(new Date());
        ztcDriver.setExamineUserId(user.getId());
        ztcDriverManager.save(ztcDriver);
        return JsonWrapper.successWrapper("操作成功！");
    }

    /**
     *冻结/启用.
     * @param did    司机id
     * @param status  状态
     * @return
     */
    @RequestMapping("setDriverStatus")
    @ResponseBody
    public HashMap<String, Object> setDriverStatus(HttpSession session,String did,String status) {
        User user = (User) session.getAttribute("userInfo");
        ZtcTransport ztcTransport1 = ztcTransportManager.get(user.getTransportId());
        if (ztcTransport1==null) {
            return JsonWrapper.failureWrapperMsg("网络错误，请稍后重试!");
        }
        //当前公司状态处于冻结状态，无法操作业务
        if (ztcTransport1.getStatus()==4) {
            return JsonWrapper.failureWrapperMsg("公司处于冻结状态，该操作不被允许!");
        }
        ZtcDriver ztcDriver = ztcDriverManager.get(did);
        if (ztcDriver == null) {
            return JsonWrapper.failureWrapperMsg("不存在该司机！");
        }
        ztcDriver.setStatus(status);
        ztcDriverManager.save(ztcDriver);
        return JsonWrapper.successWrapper("操作成功！");
    }

    //司机状态
    private String getDriverStatus(String status) {
        String temp = "";
        switch (status) {
            case "1":temp = "正常";break;
            case "2":temp = "待审核";break;
            case "3":temp = "禁用";break;
        }
        return temp;
    }
}